package com.carl.zlds.service;

import com.carl.zlds.tool.exception.GlobalException;
import com.carl.zlds.tool.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.carl.zlds.interceptor.Const;
import com.carl.zlds.interceptor.SecurityInterceptor;
import com.carl.zlds.interceptor.UserContext;
import com.carl.zlds.model.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author carl
 */
@Component("CoreAuthenticator")
public class UserAuthenticator implements SecurityInterceptor.Authenticator {

    private final ITokenService tokenService;

    @Autowired
    public UserAuthenticator(ITokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public void process(HttpServletRequest httpServletRequest) {
        String token = SecurityInterceptor.getRequiredParam(httpServletRequest, Const.REQUEST_ATTR_KEY_ACCESS_TOKEN);
        Token tokenModel = tokenService.getBaseMapper().selectOne(new QueryWrapper<Token>().eq("token", token));
        AssertUtil.isNull(GlobalException.ERROR_AUTH_FAIL,"invalid token", tokenModel);

        UserContext userContext = new UserContext();
        userContext.setUserId(tokenModel.getUserId());

        httpServletRequest.setAttribute(Const.REQUEST_ATTR_KEY_USER_CONTEXT, userContext);
        httpServletRequest.setAttribute(Const.REQUEST_ATTR_KEY_ACCESS_TOKEN, token);
    }
}
